package com.yuyue.dronesystem.controllers;

import java.util.Arrays;
import java.util.List;

import com.yuyue.dronesystem.entities.User;
import com.yuyue.dronesystem.enums.UserAuthority;
import com.yuyue.dronesystem.services.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;

/**
 * UserController
 */
@RequestMapping(path = "/main")
@Controller
public class UserController {
    
	private final String PREFIX = "main/user/";

    @Autowired
    UserService userService;

    // 查询所有用户返回列表页面
    @GetMapping(value = "/users")
    public String list(ModelMap modelMap) {
        List<User> users = userService.getUsers();
        modelMap.addAttribute("users", users);
        return PREFIX+"list";
    }

    // 来到用户添加页面
    @GetMapping(value = "/user")
    public String toAddPage(ModelMap modelMap) {
        // 查出可选的所有用户权限
        List<UserAuthority> authoritys = Arrays.asList(UserAuthority.values());
        modelMap.addAttribute("authoritys", authoritys);
        return PREFIX+"add";
    }

    // 用户添加
    @PostMapping(value = "/user")
    public String addUser(User user) {
        System.out.println("添加的用户信息："+user);
        userService.saveUser(user);
        // 返回用户列表页面
        // redirect: 重定向到一个地址
        // forward: 转发到一个地址
        return "redirect:/main/users";
    }

    // 来到用户修改页面
    @GetMapping(value = "/user/{id}")
    public String toEditPage(@PathVariable Integer id,
                             ModelMap modelMap) {
        User user = userService.getUser(id);
        modelMap.addAttribute("user", user);
        // 查出可选的所有用户权限
        List<UserAuthority> authoritys = Arrays.asList(UserAuthority.values()) ;
        modelMap.addAttribute("authoritys", authoritys);
        return PREFIX+"add";
    }

    // 用户修改，获取用户id
    @PutMapping(value = "/user")
    public String updateUser(User user) {
        System.out.println("修改的用户信息："+user);
        userService.saveUser(user);
        return "redirect:/main/users";
    }

    // 用户删除
    @DeleteMapping(value = "/user/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return "redirect:/main/users";
    }
    
}